package com.wanglibao.woodtrade.woodtrade.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.ResponseEntity;
import com.wanglibao.woodtrade.woodtrade.entity.ResponseFileAndUrl;
import com.wanglibao.woodtrade.woodtrade.entity.ResponsePictrueNameEntity;
import com.wanglibao.woodtrade.woodtrade.entity.UploadRetrueEntity;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.User;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.service.UpdateService;
import com.wanglibao.woodtrade.woodtrade.ui.activity.AboutUsActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.HomeActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.MyCommodityActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.MyDemandActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.MyOrderActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.MyShopActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.user.LoginActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.user.ModifyPasswordActivity;
import com.wanglibao.woodtrade.woodtrade.util.GetPicPath;
import com.wanglibao.woodtrade.woodtrade.util.MyView;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 个人中心
 * Created by lugg on 2016/5/10.
 */
public class UserFragment extends BaseFragment {


    @Bind(R.id.tv_commonTitle_title)
    TextView mTvCommonTitleTitle;
    @Bind(R.id.imgbtn_commonTitle_back)
    ImageButton mTvCommonTitleBack;
    @Bind(R.id.tv_commonTitle_right)
    TextView mTvCommonTitleRight;
    @Bind(R.id.sdv_user_profile_user_fragment)
    MyView mSdvUserProfileUserFragment;
    @Bind(R.id.tv_tel1_user_fragment)
    TextView mTvTel1UserFragment;
    @Bind(R.id.rl_supply_demend_activity)
    RelativeLayout mRlSupplyDemendActivity;
    @Bind(R.id.rl_my_commodity_user_fragment)
    RelativeLayout mRlMyCommodityUserFragment;
    @Bind(R.id.rl_my_order_user_fragment)
    RelativeLayout mRlMyOrderUserFragment;
    @Bind(R.id.rl_my_demand_user_fragment)
    RelativeLayout mRlMyDemandUserFragment;
    @Bind(R.id.rl_change_pwd_user_fragment)
    RelativeLayout mRlChangePwdUserFragment;
    @Bind(R.id.rl_about_us_user_fragment)
    RelativeLayout mRlAboutUsUserFragment;
    @Bind(R.id.rl_my_shop_user_fragment)
    RelativeLayout mRlMyShopUserFragment;
    @Bind(R.id.rl_common_title)
    RelativeLayout rl_common_title;
    @Bind(R.id.tv_wanglikeji_user_fragment)
    TextView tv_wanglikeji_user_fragment;
    @Bind(R.id.view_my_shop_line)
    View view_my_shop_line;
    @Bind(R.id.view_my_commodity_line)
    View view_my_commodity_line;
    @Bind(R.id.btn_fragment_user_login)
    Button btn_fragment_user_login;
    @Bind(R.id.tv_fragment_user_update)
    TextView tv_fragment_user_update;
    //==================================
    /*头像名称*/
    private String IMAGE_FILE_NAME;
    /* 请求码*/
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    public static final int EXTERNAL_STORAGE_REQ_CODE = 10;
    Context mContext;
    User user;
    ActionSheetDialog dialog;
    /*原图片路径*/
    String cameraPath;
    String photoPath;
    /*时间的转化格式*/
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /*从图库获取的图片剪辑后图片的路径*/
    Uri uri1;
    /*存放token的实体类*/
    ResponseEntity mResponseEntity = null;
    String token = null;
    /*存放上传成功后，返回json中的fileName*/
    ResponsePictrueNameEntity mNameEntity = null;
    String fileName = null;
    UploadRetrueEntity mEntity;
    public static final int TYPE_USER = 4;
    /*返回图片的Url*/
    String PictrueURl = null;
    /*判断是否是相机的操作*/
    boolean isCamera = false;
    /*联网成功的Handler*/
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg2 != 2) {
                mEntity = new Gson().fromJson(msg.obj.toString(), UploadRetrueEntity.class);
                PictrueURl = mEntity.getImg_url();
                UserImpl userImpl = new UserImpl(getContext());
                User user = userImpl.getUser();
                user.logo_url = PictrueURl;
                userImpl.update(user);
//                Picasso.with(getContext()).load(PictrueURl).placeholder(R.mipmap.ic_user_head_d).into(mSdvUserProfileUserFragment);
            }
            return false;
        }
    });

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user, container, false);
        ButterKnife.bind(this, view);
        if (Build.VERSION.SDK_INT < 19) {
            rl_common_title.setPadding(0, 0, 0, 0);
        }
        mContext = this.getActivity();
        initData();
        return view;
    }

    private void initData() {
        mTvCommonTitleTitle.setText("个人");
        mTvCommonTitleBack.setVisibility(View.GONE);
        addViewClicklistener(mRlChangePwdUserFragment, mRlMyDemandUserFragment, mRlMyOrderUserFragment, mRlMyCommodityUserFragment,
                mSdvUserProfileUserFragment, mRlMyShopUserFragment, mRlAboutUsUserFragment, btn_fragment_user_login,tv_fragment_user_update);
    }

    @Override
    public void onResume() {
        super.onResume();
        user = new UserImpl(getContext()).getUser();
        if (user != null) {
            if (!TextUtils.isEmpty(user.logo_url)) {
                Picasso.with(getContext()).load(user.logo_url).placeholder(R.mipmap.ic_user_head_d).into(mSdvUserProfileUserFragment);
            }
            mTvTel1UserFragment.setText(user.name);
            tv_wanglikeji_user_fragment.setText(user.company);
            if ("0".equals(user.is_business)) {
                mRlMyCommodityUserFragment.setVisibility(View.GONE);
                mRlMyShopUserFragment.setVisibility(View.GONE);
                view_my_commodity_line.setVisibility(View.GONE);
                view_my_shop_line.setVisibility(View.GONE);
            } else {
                mRlMyCommodityUserFragment.setVisibility(View.VISIBLE);
                mRlMyShopUserFragment.setVisibility(View.VISIBLE);
                view_my_commodity_line.setVisibility(View.VISIBLE);
                view_my_shop_line.setVisibility(View.VISIBLE);
            }
        }
    }
    /*操作权限的动态请求*/
    public void requestPermission() {
        //判断当前Activity是否已经获得了该权限
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
            } else {
                //进行权限请求
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQ_CODE);
            }
        } else {
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //头像设置
            case R.id.sdv_user_profile_user_fragment:
                requestPermission();
                IMAGE_FILE_NAME = System.currentTimeMillis() + ".jpg";
                OkHttpUtils.post().addParams("access_key", NetConfig.ACCESS_KEY)
                        .addParams("secret_key", NetConfig.SECRET_KEY)
                        .url(NetConfig.ACHIEVE_TOKEN_URL)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(okhttp3.Call call, Exception e) {
                                System.out.println("response:" + e);
                            }

                            @Override
                            public void onResponse(String response) {
                                mResponseEntity = new Gson().fromJson(response, ResponseEntity.class);
                                token = mResponseEntity.getToken();
                            }
                        });
                ActionSheetDialogNoTitle();
                break;
            //我的店铺
            case R.id.rl_my_shop_user_fragment:
                startActivity(new Intent(mContext, MyShopActivity.class));
                break;
            //我的商品
            case R.id.rl_my_commodity_user_fragment:
                startActivity(new Intent(mContext, MyCommodityActivity.class));
                break;
            //我的订单
            case R.id.rl_my_order_user_fragment:
                startActivity(new Intent(mContext, MyOrderActivity.class));
                break;
            //已发布
            case R.id.rl_my_demand_user_fragment:
                startActivity(new Intent(mContext, MyDemandActivity.class));
                break;
            //修改密码
            case R.id.rl_change_pwd_user_fragment:
                startActivity(new Intent(mContext, ModifyPasswordActivity.class));
                break;
            //关于我们
            case R.id.rl_about_us_user_fragment:
                startActivity(new Intent(mContext, AboutUsActivity.class));
                break;
            case R.id.btn_fragment_user_login:
                new UserImpl(getContext()).deleteAll();
                startActivity(new Intent(getActivity(), LoginActivity.class));
                ((HomeActivity) getActivity()).rb_home_activity_home.setChecked(true);
                break;
            case R.id.tv_fragment_user_update:
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    ToastUtil.createLongToast(getActivity(),"开始检查版本");
                    UpdateService updateService = new UpdateService(getActivity());
                    updateService.checkAppVersion(true);
                }else{
                    ToastUtil.createLongToast(getActivity(),"没有SD卡,不能进行更新");
                }
                break;
            default:
                break;
        }

    }

    //自定义dialog 用户头像的选取
    private void ActionSheetDialogNoTitle() {
        final String[] stringItems = {"拍照", "选择本地相册"};
        dialog = new ActionSheetDialog(mContext, stringItems, null);
        dialog.isTitleShow(false).show();

        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 判断存储卡是否可以用，可用进行存储
                        File file = new File(Environment.getExternalStorageDirectory().getPath()
                                + "/wood/head/");
                        if (!file.exists()) file.mkdirs();
                        //指定保存路径
                        cameraPath = Environment.getExternalStorageDirectory().getPath()
                                + "/wood/head/" + format.format(new Date()) + ".jpg";
                        File imageFile = new File(cameraPath);
                        Uri imageFileUri = Uri.fromFile(imageFile);
                        intentFromCapture.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                        intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
                        startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE);
                        dialog.dismiss();
                        break;
                    case 1:
//                        photoPath = Environment.getExternalStorageDirectory().getPath()
//                                + "/wood/head/" + format.format(new Date()) + ".jpg";
//                        Intent intentFromGallery = new Intent();
//                        intentFromGallery.setType("image/*"); // 设置文件类型
//                        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
//                        startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
                        Intent intentFromGallery = new Intent(
                                Intent.ACTION_PICK,
                                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                        startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);

                        dialog.dismiss();

                        break;
                }
            }
        });
    }

    /**
     * @param requestCode 请求码
     * @param resultCode  返回码
     * @param data        Intent的数据
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 结果码不等于取消时候
        if (resultCode == 0)
            return;
        switch (requestCode) {
            //相册请求的编码
            case IMAGE_REQUEST_CODE:
//                if (data == null) {
//                    return;
//                }
//                isFrist = true;
//                startPhotoZoom1(data.getData());
                isCamera = false;
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContext().getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                if(cursor!=null){
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    Uri uri_pic = Uri.fromFile(new File(picturePath));
                    startPhotoZoom1(uri_pic);
                }else {
                    startPhotoZoom1(data.getData());
                }


                break;
            //相机的请求编码
            case CAMERA_REQUEST_CODE:
                isCamera = true;
                startPhotoZoom(Uri.fromFile(new File(cameraPath)));
                break;
            //相机、相册的图片再 剪辑完 在这地方上传
            case RESULT_REQUEST_CODE:
                if (isCamera) {
                    upLoadPictrue(new File(cameraPath));
                } else {
                    String path = "";
                    if (android.os.Build.VERSION_CODES.KITKAT >= 19) {
                        path = new GetPicPath().getPath_above19(getActivity(), uri1);
                        System.out.println("path_above19:" + path);
                    } else {
                        path = getFilePath_below19(uri1);
                        System.out.println("path_above:" + path);
                    }
                    upLoadPictrue(new File(path));
                }

                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * API19以下获取图片路径的方法
     *
     * @param uri
     */
    private String getFilePath_below19(Uri uri) {
        //这里开始的第二部分，获取图片的路径：低版本的是没问题的，但是sdk>19会获取不到
        String[] proj = {MediaStore.Images.Media.DATA};
        //好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = getContext().getContentResolver().query(uri, proj, null, null, null);
        //获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        System.out.println("***************" + column_index);
        //将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        //最后根据索引值获取图片路径   结果类似：/mnt/sdcard/DCIM/Camera/IMG_20151124_013332.jpg
        String path = cursor.getString(column_index);
        System.out.println("path:" + path);
        return path;
    }

    /**
     * @param file 上传的图片
     */
    public void upLoadPictrue(final File file) {
        uri1 = Uri.fromFile(file);
        if (token != null) {
            OkHttpUtils.post()
                    .addParams("token", token)
                    .addFile("filename", IMAGE_FILE_NAME, file)
                    .url(NetConfig.PICTRUE_UPLOAD_URL)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(okhttp3.Call call, Exception e) {

                        }

                        @Override
                        public void onResponse(String response) {
                            System.out.println("response:" + response);
                            mNameEntity = new Gson().fromJson(response, ResponsePictrueNameEntity.class);
                            fileName = mNameEntity.getErr_msg();
                            ResponseFileAndUrl fileAndUrl=new Gson().fromJson(mNameEntity.getErr_msg().toString(),ResponseFileAndUrl.class);
                            Picasso.with(getContext()).load(fileAndUrl.getFilename().getUrl()).placeholder(R.mipmap.ic_user_head_d).into(mSdvUserProfileUserFragment);
                            NetWorking(fileAndUrl.getFilename().getName());
                        }
                    });
        }
    }

    /**
     * @param fileName 上传图片的名字
     */
    public void NetWorking(String fileName) {
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_COMMON,
                NetConfig.imgUpload, mHandler,
                "jsonObject", NetConfig.TaskId.imgUpload, new Object[]{user.id, TYPE_USER, fileName, user.token});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    /**
     * 相机拍照的裁剪图片方法
     *
     * @param uri 图片的uri路径
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//可裁剪
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);//若为false则表示不返回数据
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /**
     * 相册的裁剪图片方法
     *
     * @param uri 相册的uri路径 裁剪到指定的路径 uri1
     */
    public void startPhotoZoom1(Uri uri) {
        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                "yyyy_MM_dd_HH_mm_ss");
        File file = new File(Environment.getExternalStorageDirectory().getPath()
                + "/wood/head/");
        if (!file.exists()) file.mkdirs();
        //指定保存路径
        String photoPath = Environment.getExternalStorageDirectory().getPath()
                + "/wood/head/" + timeStampFormat.format(new Date()) + ".jpg";
        if (uri == null) {
            System.out.println("The uri is not exist.");
        }
        File file1 = new File(photoPath);
        uri1 = Uri.fromFile(file1);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");//可裁剪
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri1);
        intent.putExtra("return-data", false);//若为false则表示不返回数据
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (this.getView() != null)
            this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
